package org.bjf.demo;


import org.bjf.modules.core.web.core.LoginInfo;
import org.bjf.modules.core.web.core.ThreadContext;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author bjf on 2020/11/4
 * @version 1.0
 */
public class ThreadPoolExecutorWrap extends ThreadPoolExecutor {


    public ThreadPoolExecutorWrap(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);

    }

    @Override
    public Future<?> submit(Runnable task) {
        return super.submit(new RunnableWrap((task)));
    }

    @Override
    public <T> Future<T> submit(Runnable task, T result) {
        return super.submit(new RunnableWrap((task)), result);
    }

    @Override
    public void execute(Runnable task) {
        super.execute(new RunnableWrap((task)));
    }


    static class RunnableWrap implements Runnable {
        //初始化获取线程上下文
        private LoginInfo loginInfo = ThreadContext.getLoginInfo();
        private Runnable task;

        public RunnableWrap(Runnable task) {
            this.task = task;
        }

        @Override
        public void run() {
            try {
                ThreadContext.setLoginInfo(loginInfo);
                // 用户业务逻辑
                task.run();
            } finally {
                // 释放资源
            }
        }
    }
}